package com.gftBrazil.BankSystem.view;

import com.gftBrazil.BankSystem.bean.UsuarioBean;
import com.gftBrazil.BankSystem.bean.enums.Permissao;
import com.gftBrazil.BankSystem.exceptions.AcessoNegadoException;
import com.gftBrazil.BankSystem.sistema.Sessao;
import com.gftBrazil.BankSystem.util.Ambiente;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author JRSS
 */
public class LoginView extends javax.swing.JDialog {

    private List<UsuarioBean> usuarios;
    private final UsuarioBean usuario;
    private final Permissao permissaoAcesso;

    /**
     * Creates new form Login
     *
     * @param parent
     * @param modal
     */
    public LoginView(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        usuario = new UsuarioBean();
        this.permissaoAcesso = Permissao.ACESSO_SISTEMA;
        initComponents();
        initListeners();
        carregarUsuarios();
    }

    private void initListeners() {
        this.tLogin.addKeyListener(trataTeclas);
        this.tSenha.addKeyListener(trataTeclas);
        this.bEntrar.addKeyListener(trataTeclas);

        this.bEntrar.addActionListener(trataBotoes);
        this.bAlterarSenha.addActionListener(trataBotoes);
        this.bSair.addActionListener(trataBotoes);
    }

    private void carregarUsuarios() {
        usuarios = new ArrayList<>();
        UsuarioBean u;
        for (int i = 0; i < 10; i++) {
            u = new UsuarioBean();
            u.setLogin("login" + (i + 1));
            u.setSenha("123" + (i + 1));
            Set<Permissao> permissoes = new TreeSet<>();
            permissoes.add(Permissao.ACESSO_SISTEMA);
            permissoes.add(Permissao.CONSULTAR_CLIENTE);
            permissoes.add(Permissao.ALTERAR_CLIENTE);
            permissoes.add(Permissao.CADASTRAR_CLIENTE);
            u.setPermissoes(permissoes);
            usuarios.add(u);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        lLogin = new javax.swing.JLabel();
        tLogin = new javax.swing.JTextField();
        lSenha = new javax.swing.JLabel();
        tSenha = new javax.swing.JPasswordField();
        bEntrar = new javax.swing.JButton();
        bAlterarSenha = new javax.swing.JButton();
        bSair = new javax.swing.JButton();
        tMensagem = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Acesso ao sistema");
        getContentPane().setLayout(new java.awt.GridBagLayout());

        lLogin.setText("Login:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        getContentPane().add(lLogin, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 5.0;
        getContentPane().add(tLogin, gridBagConstraints);

        lSenha.setText("Senha:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        getContentPane().add(lSenha, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 5.0;
        getContentPane().add(tSenha, gridBagConstraints);

        bEntrar.setText("Entrar");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(bEntrar, gridBagConstraints);

        bAlterarSenha.setText("Alterar senha");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(bAlterarSenha, gridBagConstraints);

        bSair.setText("Sair");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(bSair, gridBagConstraints);

        tMensagem.setText(" ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(tMensagem, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                LoginView dialog = new LoginView(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private final class TrataTeclas implements KeyListener {

        @Override
        public void keyTyped(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyPressed(KeyEvent ke) {
            if (ke.getKeyCode() == KeyEvent.VK_TAB || ke.getKeyCode() == KeyEvent.VK_ENTER) {
                if (ke.getSource() == tLogin) {
                    tSenha.requestFocus();
                } else if (ke.getSource() == tSenha) {
                    bEntrar.requestFocus();
                } else if (ke.getSource() == bEntrar && ke.getKeyCode() == KeyEvent.VK_ENTER) {
                    if (validaCampos()) {
                        try {
                            verificarUsuarioSenha();
                            dispose();
                        } catch (AcessoNegadoException ex) {
                            Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        }

        @Override
        public void keyReleased(KeyEvent ke) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    }

    private final class TrataBotoes implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == bEntrar) {
                if (validaCampos()) {
                    try {
                        verificarUsuarioSenha();
                        dispose();
                    } catch (AcessoNegadoException ex) {
                        Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            } else if (ae.getSource() == bAlterarSenha) {
                /**
                 * Falta implementar
                 */
                JOptionPane.showMessageDialog(null,
                        "Em fase de implementacao",
                        "Implementacao",
                        JOptionPane.WARNING_MESSAGE);
            } else if (ae.getSource() == bSair) {
                Ambiente.getUsuario().setPermissoes(null);
                dispose();
            }
        }
    }

    private boolean validaCampos() {
        boolean sucess = true;
        String login = tLogin.getText();
        String senha = tSenha.getPassword().toString();
        if (login == null || senha == null) {
            return false;
        }
        if (login.isEmpty() || senha.isEmpty()) {
            return false;
        }
        return sucess;
    }

    private void verificarUsuarioSenha() throws AcessoNegadoException {
        String login = tLogin.getText();
        String senha = new String(tSenha.getPassword());
        boolean achei = false;
        for (UsuarioBean u : usuarios) {
            if (u.getLogin().equals(login) && u.getSenha().equals(senha) && u.getPermissoes().contains(permissaoAcesso)) {
                usuario.setLogin(login);
                usuario.setSenha(senha);
                usuario.setPermissoes(u.getPermissoes());
                Ambiente.setUsuario(usuario);
                Sessao.getInstance().setUsuario(usuario);
                achei = true;
            }
        }
        if (!achei) {
            tMensagem.setText("Acesso negado!");
            throw new AcessoNegadoException("E nessario: ", permissaoAcesso);
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bAlterarSenha;
    private javax.swing.JButton bEntrar;
    private javax.swing.JButton bSair;
    private javax.swing.JLabel lLogin;
    private javax.swing.JLabel lSenha;
    private javax.swing.JTextField tLogin;
    private javax.swing.JLabel tMensagem;
    private javax.swing.JPasswordField tSenha;
    // End of variables declaration//GEN-END:variables
    private final TrataTeclas trataTeclas = new TrataTeclas();
    private final TrataBotoes trataBotoes = new TrataBotoes();
}
